
package todolist.logic.parser;

import java.util.Date;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import todolist.personalization.DateTimePatternCustomizer;

/**
 * Parser of only Temporal information according to predefined patterns.
 * @author Ivan
 */
public class DateParser {
	
	/**
	 * Tries to parse String containing Date+Time information only.
	 * If no match found, null Date returned.
	 */
	public Date parseDateTime(String pstrInput) {
		return parsePatterns(DateTimePatternCustomizer.getInstance().getInputDateTimePatterns(), pstrInput);
	}

	/**
	 * Tries to parse String containing Date information only, no Time.
	 * If no match found, null Date returned.
	 */
	public Date parseDateOnly(String pstrInput) {
		return parsePatterns(DateTimePatternCustomizer.getInstance().getInputDateOnlyPatterns(), pstrInput);
	}
	
	// private methods

	/**
	 * Tries to parse input according to an array of patterns.
	 * If no match found, null Date returned.
	 */
	private Date parsePatterns(String[] parrPatterns, String pstrInput) {
		// parameter validation
		if (pstrInput == null)
			return null;
		pstrInput = pstrInput.trim().toUpperCase();
		if (pstrInput.length() == 0)
			return null;
		// try to parse input from each pattern
		for (String strPattern : parrPatterns) {
			SimpleDateFormat objSDF = new SimpleDateFormat(strPattern);
			objSDF.setLenient(false);
			ParsePosition objPP = new ParsePosition(0);
			Date dtmParsed = objSDF.parse(pstrInput, objPP);
			if (objPP.getErrorIndex() != -1) // if error found, try other patterns
				continue;
			return dtmParsed;
		}
		return null; // no match found
	}
	
}
